// componnets/cartAdder/cartAdder.js
import store from '../../modules/store'
import tool from '../../modules/tool'
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    iid: {
      type: Number,
      default: -1
    },
    isPro: {
      type: Boolean,
      default: true
    },
    item: {
      type: Object,
      default: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    num: 0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    update() {
      let n = 0
      let t = store.getItem('cartList')
      for (let i = 0; i < t.length; i++) {
        if (t[i].itemId == this.properties.iid && t[i].isPro == this.properties.isPro) {
          n++
        }
      }
      // console.log(n)
      this.setData({
        num: n
      })
    },
    async handleAdd() {
      if (!this.properties.isPro) {
        let re = await tool.requestData('/getServerTime', {}, 'get')
        if (re.status) {
          let now = new Date(re.data)
          let startReg = new Date(this.properties.item.startRegistration)
          let endReg = new Date(this.properties.item.endRegistration)
          let startTime = new Date(this.properties.item.startTime)
          let endTime = new Date(this.properties.item.endTime)
          console.log(startReg, now, endReg)
          if (now > startReg && now < endReg) {
            //允许报名
          } else {
            tool.handleShowToast('不在报名时间范围内', 'error')
            return
          }
        } else {
          tool.handleShowToast('操作失败', 'error')
          return
        }
      }
      let t = this.properties.item
      t.isPro = this.properties.isPro ? 1 : 0
      store.setItem('indexShowPayBoard', t)
    },
    async handleDelete() {
      let re = await tool.requestData('/cart/deleteTop', {
        openId: store.getItem('userData').openId,
        isPro: this.properties.isPro ? 1 : 0,
        itemId: this.properties.iid
      })
      if (re.status) {
        await tool.handleUpdateCartNum()
      } else {
        tool.handleShowToast('操作失败', 'error')
      }
    }
  },

  attached() {
    this.update()
    store.onChange('cartList', () => {
      this.update()
    })
  }
})